<template>
  <div>
    <h2>合作商管理</h2>
    电话号码：<el-input placeholder="请输入手机号" v-model="user.tel" style="width: 200px"></el-input><br>
    短息验证码：<el-input placeholder="请输入验证码" v-model="user.telCode" style="width: 200px"></el-input><br>
    <el-button :disabled="disabled" @click="getTelCode">{{time}}</el-button>
    <br>
    <el-button @click="login" type="info">登录</el-button>
    <br>
  </div>
</template>

<script>
import { v4 as uuidv4 } from 'uuid'
export default {
  name: 'LoginView',
  data () {
    return {
      disabled: false,
      time: '发送验证码',
      user: {
        tel: '',
        telCode: '',
        codeKey: ''
      }
    }
  },
  methods: {
    // 发送验证码
    getTelCode () {
      this.user.codeKey = uuidv4()
      this.axios.post('/user/getTelCode', this.user).then(res => {
        if (res.data.jdata === 200) {
          this.$message.success('发送成功')
        }
      })
      // 验证码有效期 定时器
      this.time = 300
      this.disabled = true
      const timer = setInterval(() => {
        this.time = this.time - 1
        if (this.time === 0) {
          clearInterval(timer)
          this.disabled = false
          this.time = '发送验证码'
        }
      }, 1000)
    },
    // 登录
    login () {
      this.axios.post('/user/mylogin', this.user).then(res => {
        if (res.data.code === 200) {
          this.$store.commit('setToken', res.data.jdata.token)
          this.$store.commit('setUser', res.data.jdata.user)
          this.$message.success('登陆成功')
          if (res.data.jdata.user.role === 'admin') {
            this.$router.push('/list')
          }
        } else if (res.data.code === 911) {
          this.$message.error('手机号错误')
        } else if (res.data.code === 909) {
          this.$message.error('验证码错误')
        } else if (res.data.code === 910) {
          this.$message.error('用户不存在')
        } else {
          this.$message.error('no')
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
